package Formularios;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class frmBuscarClientes extends JFrame {

	private JPanel contentPane;
	private JTextField txtNumCliente;
	private JTextField txtNombre;
	private JTextField txtApellidoP;
	private JTextField txtApellidoM;
	private JTable table;
	
	//NEMONICOS
	static final int COL_CODIGO = 0;
	static final int COL_NOMBRE = 1;
	static final int COL_APELLIDO_PATERNO = 2;
	static final int COL_APELLIDO_MATERNO = 3;
	
	static final int CAMPO_NOMBRE = 1;
	static final int CAMPO_APELLIDOP = 2;
	static final int CAMPO_APELLIDOM = 3;
	
	static Statement comando;
	static Connection con;
	int iRenglon = 0;
	int iCodigo = 0;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					frmBuscarClientes frame = new frmBuscarClientes();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public frmBuscarClientes() {
		setTitle("Busqueda De Clientes");
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 743, 504);
		
		general gen = new general();
		try {
			comando = gen.abrirConexion(cNemonicos.IP_GLOBAL,1);
		} catch (ClassNotFoundException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		} catch (SQLException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		
		JLabel lblNumCliente = new JLabel("# Cliente :");
		
		txtNumCliente = new JTextField();
		txtNumCliente.addKeyListener(new KeyAdapter() {
			@Override
			public void keyTyped(KeyEvent e) {
				char c = e.getKeyChar();
				if ((!(Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)))) {
					getToolkit().beep();
					e.consume();
				}
				if (txtNumCliente.getText().length() == 3) {
					e.consume();
				}
			}
		});
		txtNumCliente.setColumns(10);
		
		JLabel lblNombre = new JLabel("Nombre :");
		
		txtNombre = new JTextField();
		txtNombre.addKeyListener(new KeyAdapter() {
			@Override
			public void keyTyped(KeyEvent e) {
				char c = e.getKeyChar();
				if (((Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)))) {
					getToolkit().beep();
					e.consume();
				}
				else
				{
					buscarClientes(4,txtNombre.getText(),txtApellidoP.getText(),txtApellidoM.getText());	
				}
				if (txtNombre.getText().length() == 25) {
					e.consume();
				}
			}
			@Override
			public void keyPressed(KeyEvent e) {
				if (e.getKeyCode() == cNemonicos.VK_ABAJO )
				{
					table.requestFocus();
				}
			}
		});
		
		txtNombre.setColumns(10);
		
		JLabel lblApellidoP = new JLabel("Apellido P :");
		
		txtApellidoP = new JTextField();
		txtApellidoP.addKeyListener(new KeyAdapter() {
			@Override
			public void keyTyped(KeyEvent e) {
				char c = e.getKeyChar();
				if (((Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)))) {
					getToolkit().beep();
					e.consume();
				}
				else
				{
					buscarClientes(4,txtNombre.getText(),txtApellidoP.getText(),txtApellidoM.getText());
				}
				if (txtApellidoP.getText().length() == 25) {
					e.consume();
				}
			}
			@Override
			public void keyPressed(KeyEvent e) {
				if (e.getKeyCode() == cNemonicos.VK_ABAJO )
				{
					table.requestFocus();
				}
			}
		});
		txtApellidoP.setColumns(10);
		
		JLabel lblApellidoM = new JLabel("Apellido M :");
		
		txtApellidoM = new JTextField();
		txtApellidoM.addKeyListener(new KeyAdapter() {
			@Override
			public void keyTyped(KeyEvent e) {
				char c = e.getKeyChar();
				if (((Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)))) {
					getToolkit().beep();
					e.consume();
				}
				else
				{
					buscarClientes(4,txtNombre.getText(),txtApellidoP.getText(),txtApellidoM.getText());	
				}
				if (txtApellidoM.getText().length() == 25) {
					e.consume();
				}
			}
			@Override
			public void keyPressed(KeyEvent e) {
				if (e.getKeyCode() == cNemonicos.VK_ABAJO )
				{
					table.requestFocus();
				}
			}
		});
		txtApellidoM.setColumns(10);
		
		JScrollPane scrollPane = new JScrollPane();
		GroupLayout gl_contentPane = new GroupLayout(contentPane);
		gl_contentPane.setHorizontalGroup(
			gl_contentPane.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentPane.createSequentialGroup()
					.addContainerGap()
					.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_contentPane.createSequentialGroup()
							.addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING)
								.addComponent(lblNumCliente)
								.addComponent(lblNombre))
							.addPreferredGap(ComponentPlacement.RELATED)
							.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
								.addGroup(gl_contentPane.createSequentialGroup()
									.addComponent(txtNombre, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
									.addPreferredGap(ComponentPlacement.UNRELATED)
									.addComponent(lblApellidoP)
									.addPreferredGap(ComponentPlacement.RELATED)
									.addComponent(txtApellidoP, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
									.addPreferredGap(ComponentPlacement.UNRELATED)
									.addComponent(lblApellidoM)
									.addPreferredGap(ComponentPlacement.RELATED)
									.addComponent(txtApellidoM, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
								.addComponent(txtNumCliente, GroupLayout.PREFERRED_SIZE, 59, GroupLayout.PREFERRED_SIZE)))
						.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 710, GroupLayout.PREFERRED_SIZE))
					.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
		);
		gl_contentPane.setVerticalGroup(
			gl_contentPane.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentPane.createSequentialGroup()
					.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblNumCliente)
						.addComponent(txtNumCliente, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addPreferredGap(ComponentPlacement.RELATED)
					.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
						.addComponent(txtNombre, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(lblApellidoP)
						.addComponent(txtApellidoP, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(lblApellidoM)
						.addComponent(txtApellidoM, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(lblNombre))
					.addPreferredGap(ComponentPlacement.RELATED, 60, Short.MAX_VALUE)
					.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 345, GroupLayout.PREFERRED_SIZE)
					.addContainerGap())
		);
		
		table = new JTable();
		table.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				if ( e.getKeyCode() == cNemonicos.VK_SALTO_DE_LINEA )
				{
					int iRen = table.getSelectedRow();
					iCodigo = (int) table.getValueAt(iRen, COL_CODIGO);
					dispose();
				}
			}
		});
		table.setModel(new DefaultTableModel(
			new Object[][] {
				{null, null, null, null},
				{null, null, null, null},
				{null, null, null, null},
				{null, null, null, null},
				{null, null, null, null},
				{null, null, null, null},
				{null, null, null, null},
				{null, null, null, null},
				{null, null, null, null},
				{null, null, null, null},
				{null, null, null, null},
				{null, null, null, null},
				{null, null, null, null},
				{null, null, null, null},
				{null, null, null, null},
				{null, null, null, null},
				{null, null, null, null},
				{null, null, null, null},
				{null, null, null, null},
				{null, null, null, null},
				{null, null, null, null},
				{null, null, null, null},
				{null, null, null, null},
				{null, null, null, null},
				{null, null, null, null},
				{null, null, null, null},
				{null, null, null, null},
				{null, null, null, null},
				{null, null, null, null},
				{null, null, null, null},
			},
			new String[] {
				"Codigo", "Nombre", "Apellido Paterno", "Apellido Materno"
			}
		) {
			Class[] columnTypes = new Class[] {
				Integer.class, String.class, String.class, Object.class
			};
			public Class getColumnClass(int columnIndex) {
				return columnTypes[columnIndex];
			}
		});
		
		DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();
		tcr.setHorizontalAlignment(SwingConstants.CENTER);
				
		table.getColumnModel().getColumn(0).setResizable(false);
		table.getColumnModel().getColumn(0).setMaxWidth(75);
		table.getColumnModel().getColumn(0).setCellRenderer(tcr);
		table.getColumnModel().getColumn(1).setResizable(false);
		table.getColumnModel().getColumn(1).setMaxWidth(200);
		table.getColumnModel().getColumn(1).setCellRenderer(tcr);
		table.getColumnModel().getColumn(2).setResizable(false);
		table.getColumnModel().getColumn(2).setPreferredWidth(121);
		table.getColumnModel().getColumn(2).setMinWidth(75);
		table.getColumnModel().getColumn(2).setMaxWidth(400);
		table.getColumnModel().getColumn(2).setCellRenderer(tcr);
		table.getColumnModel().getColumn(3).setResizable(false);
		table.getColumnModel().getColumn(3).setPreferredWidth(121);
		table.getColumnModel().getColumn(3).setMinWidth(75);
		table.getColumnModel().getColumn(3).setMaxWidth(400);
		table.getColumnModel().getColumn(3).setCellRenderer(tcr);
		//centrarCeldas();
		scrollPane.setViewportView(table);
		contentPane.setLayout(gl_contentPane);
	}
	
	public boolean buscarClientes(int iCampo, String sDesc, String sApeP, String sApeM) {

		boolean bRespuesta = true;
		String sNombre = "", sApellidoP = "", sApellidoM = "";
		String query = null;
		int iNumCliente = 0;
		sDesc = sDesc.toUpperCase();
		sApeP = sApeP.toUpperCase();
		sApeM = sApeM.toUpperCase();
		limpiarGrid();
		try {

			switch (iCampo) {
			case CAMPO_NOMBRE:
				// Una variable String para almacenar la sentencia SQL
				query = "select numcliente,trim(nombre) as nombre,trim(apellidop) as apellidop,trim(apellidom) as apellidom from caclientes  where Upper(nombre) like '%" + sDesc + "%' ;";
				break;
			case CAMPO_APELLIDOP:
				// Una variable String para almacenar la sentencia SQL
				query = "select numcliente,trim(nombre) as nombre,trim(apellidop) as apellidop,trim(apellidom) as apellidom from caclientes  where Upper(apellidop) like '%" + sDesc + "%' ;";
				break;
			case CAMPO_APELLIDOM:
				// Una variable String para almacenar la sentencia SQL
				query = "select numcliente,trim(nombre) as nombre,trim(apellidop) as apellidop,trim(apellidom) as apellidom from caclientes  where Upper(apellidom) like '%" + sDesc + "%' ;";
				break;
				
			case 4:
				// Una variable String para almacenar la sentencia SQL
				query = "select numcliente,trim(nombre) as nombre,trim(apellidop) as apellidop,trim(apellidom) as apellidom from caclientes  where Upper(nombre) like '%" + sDesc + "%'" +
						"and Upper(apellidop) like '%" + sApeP + "%' and Upper(apellidom) like '%" + sApeM + "%' ;";
				break;

			default:
				break;
			}
			ResultSet resultado = comando.executeQuery(query);

			// Ejecutamos la consulta SQL
			while (resultado.next()) {
				iNumCliente = resultado.getInt("numcliente");
				sNombre = resultado.getString("nombre");
				sApellidoP = resultado.getString("apellidop");
				sApellidoM = resultado.getString("apellidom");
				
				table.setValueAt(iNumCliente, iRenglon, COL_CODIGO);
				table.setValueAt(sNombre, iRenglon, COL_NOMBRE);
				table.setValueAt(sApellidoP, iRenglon, COL_APELLIDO_PATERNO);
				table.setValueAt(sApellidoM, iRenglon, COL_APELLIDO_MATERNO);
				iRenglon++;
			}

		} catch (SQLException e) {
			bRespuesta = false;
			// Por si ocurre un error
			System.out.println(e.getMessage());
			int op = JOptionPane.showOptionDialog(null, e.getMessage(),
					"Entrada Invalidad", JOptionPane.YES_OPTION,
					JOptionPane.ERROR_MESSAGE, null,
					new Object[] { "ACEPTAR" }, "ACEPTAR");
			if (op == 0) {

			}
		}

		return bRespuesta;
	}
	public void limpiarGrid()
	{		
		for (int iRen = 0; iRen < table.getRowCount(); iRen++) {
			table.setValueAt(null,iRen, COL_CODIGO);
			table.setValueAt(null,iRen, COL_NOMBRE);
			table.setValueAt(null,iRen, COL_APELLIDO_PATERNO);
			table.setValueAt(null,iRen, COL_APELLIDO_MATERNO);
		}
		iRenglon = 0;
	}
	
	public void centrarCeldas()
	{
		//centrar celdas
		DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();
		tcr.setHorizontalAlignment(SwingConstants.CENTER);
		for (int iRen = 0; iRen < table.getRowCount(); iRen++) 
		{
			table.getColumnModel().getColumn(iRen).setCellRenderer(tcr);
		}
	}
	
	public int getCodigo()
	{
		int iCodigo2 = iCodigo;
		return iCodigo2;
		
	}
}
